package co.gov.medellin.sdep.sisdep.model.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.jdbc.object.MappingSqlQuery;
import org.springframework.jdbc.object.SqlUpdate;

import co.gov.medellin.sdep.sisdep.model.Local;

public class LocalDAOImpl extends JdbcDaoSupport implements ILocalDAO {

    private InsertOperation insertOperation;

    private UpdateOperation updateOperation;

    private DeleteOperation deleteOperation;

    private DeleteByPrimaryKey deleteByPrimaryKey;

    private FindByPrimaryKeyQuery findByPrimaryKeyQuery;

    private FindByCriteriaQuery findByCriteriaQuery;

    private FindAllQuery findAllQuery;
    
    private ListaLocales listaLocales;
    
    private ListaLocalesPorCCO listaLocalesPorCCO;
    
    private FindByNumeroLocalQuery findByNumeroLocalQuery;

    private FindByActiveStateQuery findByActiveStateQuery;

	private static final String SELECT = "SELECT * FROM CCO_LOCAL_T ";
	private static final String WHERE = " WHERE ";
	private static final String PARAMETER = " ?, ";

    public void delete(Local local) {
		deleteOperation.execute( local  );
	}

	public void deleteByPrimaryKey(long id) {
		deleteByPrimaryKey.execute(id);
	}

	public Local findByPrimaryKey(long login) {
		return findByPrimaryKeyQuery.runQuery(login);
	}

	public void insert(Local local) {
		insertOperation.execute( local );
	}

	public void update(Local local) {
		updateOperation.execute( local );
	}

	public Local findByCriteria(Local  local) {
		return findByCriteriaQuery.runQuery(local);
	}

	public List load() {
		return findAllQuery.runQuery();
	}
	
	public List loadByNumeroLocal(Local local) {
		return findByNumeroLocalQuery.runQuery(local);
	}
	
	public List listaLocales() {
		return listaLocales.runQuery();
	}

	public List listaLocalesPorCCO(Long idCentroComercial) {
		return listaLocalesPorCCO.runQuery(idCentroComercial);
	}
	
	public Local findByActiveState(Local  local) {
		return findByActiveStateQuery.runQuery(local);
	}

	public void initDao() {
    	insertOperation   = new InsertOperation( getDataSource() );
    	updateOperation = new UpdateOperation(  getDataSource() );
    	//deleteOperation = new DeleteOperation(  getDataSource() );
    	//deleteByPrimaryKey = new DeleteByPrimaryKey( getDataSource());
    	//findByPrimaryKeyQuery   = new FindByPrimaryKeyQuery(  getDataSource() );
    	//findByCriteriaQuery = new FindByCriteriaQuery(  getDataSource() );
    	findAllQuery = new FindAllQuery( getDataSource() );
    	findByNumeroLocalQuery = new FindByNumeroLocalQuery( getDataSource() );
    	listaLocales = new ListaLocales(getDataSource());
    	listaLocalesPorCCO = new ListaLocalesPorCCO(getDataSource());
    	//findByActiveStateQuery = new FindByActiveStateQuery( getDataSource() );
    }

    // ------------- SaveOperation ---------------------------------------
	class InsertOperation extends SqlUpdate	{
		private static final String sql = "INSERT INTO CCO_LOCAL_T ("
				  + " ID, "
				  + " ID_CENTRO_COMERCIAL, "
				  + " NUMERO_LOCAL, "
				  + " AREA, "
				  + " OBSERVACION, "
				  + " ESTADO_FINANCIERO, "
				  + " ESTADO, "
				  + " USUARIO_CREA, "
				  + " FECHA_CREA "				  
				  + ") VALUES ("
			  	  + " CCO_LOCAL_SEC.nextVal, "
				  + PARAMETER
				  + PARAMETER
				  + PARAMETER
				  + PARAMETER
				  + PARAMETER
				  + PARAMETER
				  + PARAMETER
				  + "SYSDATE"
				  + ")";
		public  InsertOperation(DataSource ds) {
			super(ds,sql);
			//set here required parameters
			declareParameter( new SqlParameter(Types.INTEGER));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));			
			compile();
		}
		public void execute(Local local) {
			InsertOperation.this.update( new Object[]{
				local.getIdCentroComercial(),
				local.getNumeroLocal(),
				local.getAreaStr(),
				local.getObservacion(),
				local.getEstadoFinanciero(),
				local.getEstado(),
				local.getUsuarioCrea()				
				});
		}
    }

    // ------------- UpdateOperation -------------------------------------
    class UpdateOperation extends SqlUpdate	{
    	private static final String sql = "UPDATE CCO_LOCAL_T SET "					  
    		  		  + " ID_CENTRO_COMERCIAL = ? ,"
    				  + " NUMERO_LOCAL = ? ,"
					  + " AREA = ? ,"
					  + " OBSERVACION = ? ,"
					  + " ESTADO_FINANCIERO = ? ,"
					  + " ESTADO = ? ,"					  
					  + " USUARIO_MODIFICA = ? ,"
					  + " FECHA_MODIFICA = SYSDATE"
				  	  + WHERE
				  	  + " ID = ? ";
		public  UpdateOperation(DataSource ds) {
			super(ds,sql);
			//set here required parameters		
			declareParameter( new SqlParameter(Types.INTEGER));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.INTEGER));
			compile();
		}
		public void execute(Local local) {
			UpdateOperation.this.update( new Object[]{		
				local.getIdCentroComercial(),
				local.getNumeroLocal(),
				local.getAreaStr(),
				local.getObservacion(),
				local.getEstadoFinanciero(),
				local.getEstado(),				
				local.getUsuarioModifica(),
				local.getId()
				});
		}
    }

    // ------------- DeleteOperation -------------------------------------
    class DeleteOperation extends SqlUpdate	{
		private static final String sql = "DELETE FROM CCO_LOCAL_T "
										+ WHERE + "1=1";
		public DeleteOperation(DataSource ds) {
			super(ds,sql);
			compile();
		}
		public void execute(Local local) {
			this.update( new Object[]{
			});
		}
	}

    // ------------- DeleteByPrimaryKey ----------------------------------
    class DeleteByPrimaryKey extends SqlUpdate	{
		private static final String sql = "DELETE FROM CCO_LOCAL_T "
										+ WHERE  + "1=1";
		public DeleteByPrimaryKey(DataSource ds) {
			super(ds,sql);
			compile();
		}	
		public void execute(long id) {
			this.update( new Object[]{
			});
		}	
    }

    // ---- BaseQueryOperation for Mapping ResultSet values --------------
	abstract class BaseQueryOperation extends MappingSqlQuery {
		public BaseQueryOperation(DataSource ds,String sql) {
	   		super(ds,sql);
		}	
		protected Object mapRow(ResultSet rs, int rownum) throws SQLException {
			Local local = new Local();
				local.setId(new Long(rs.getLong("ID")));
				local.setIdCentroComercial(new Long(rs.getLong("ID_CENTRO_COMERCIAL")));
				local.setIdCentroComercialStr(rs.getString("ID_CENTRO_COMERCIAL"));
				local.setNumeroLocal(rs.getString("NUMERO_LOCAL"));				
				local.setAreaStr(rs.getString("AREA"));
				local.setObservacion(rs.getString("OBSERVACION"));
				local.setEstadoFinanciero(rs.getString("ESTADO_FINANCIERO"));
				local.setEstado(rs.getString("ESTADO"));
				local.setUsuarioCrea(rs.getString("USUARIO_CREA"));
				local.setFechaCrea(rs.getDate("FECHA_CREA"));		
				local.setUsuarioModifica(rs.getString("USUARIO_MODIFICA"));
				local.setFechaModifica(rs.getDate("FECHA_MODIFICA"));		
			return local;
		}
    }

    // ---- BaseQueryOperation for Mapping ResultSet values --------------
	abstract class ListaCentroComercialQueryOperation extends MappingSqlQuery {
		public ListaCentroComercialQueryOperation(DataSource ds,String sql) {
	   		super(ds,sql);
		}	
		protected Object mapRow(ResultSet rs, int rownum) throws SQLException {
				ArrayList typeValueList = new ArrayList();
				String registro[] = {"0","0"};
				registro[0]= rs.getString("ID");
				registro[1]= rs.getString("NOMBRE");
				typeValueList.add(registro);
				registro = null;
			return typeValueList;
		}
    }
    // ------------- FindByPrimaryKeyQuery -------------------------------
    class FindByPrimaryKeyQuery extends BaseQueryOperation {
		private static final String sql = SELECT
										+ WHERE  + "1=1";
    	public FindByPrimaryKeyQuery(DataSource ds) {
    		super(ds,sql);
			compile();
    	}
    	public Local runQuery(long id) {
			List result =  execute( new Object[]{new Long(id)});
			if ( result.size() > 0 ) {
        		return (Local) result.get(0);
        	} else {
        		return null;
        	}
    	}
    }

    // ------------- FindByCriteriaQuery ---------------------------------    
    class FindByCriteriaQuery extends BaseQueryOperation {
		private static final String sql = SELECT
										+ WHERE + " 1=1 ";
			//For required criteria elements uncomment required values
			  	  	  					//+ " AND ID = ? "
			  	  	  					//+ " AND NUMERO_LOCAL = ? "
			  	  	  					//+ " AND AREA = ? "
			  	  	  					//+ " AND OBSERVACION = ? "
			  	  	  					//+ " AND ESTADO_FINANCIERO = ? "
			  	  	  					//+ " AND ESTADO = ? "
			  	  	  					//+ " AND USUARIO_CREA = ? "
			  	  	  					//+ " AND FECHA_CREA = ? "
			  	  	  					//+ " AND USUARIO_MODIFICA = ? "
			  	  	  					//+ " AND FECHA_MODIFICA = ? "
										//+ "";
    	public FindByCriteriaQuery(DataSource ds) {
    		super(ds,sql);
    		//For required criteria elements uncomment required values
			//declareParameter( new SqlParameter(Types.INTEGER) );
			//declareParameter( new SqlParameter(Types.CHAR) );
			//declareParameter( new SqlParameter(Types.INTEGER) );
			//declareParameter( new SqlParameter(Types.CHAR) );
			//declareParameter( new SqlParameter(Types.CHAR) );
			//declareParameter( new SqlParameter(Types.CHAR) );
			//declareParameter( new SqlParameter(Types.CHAR) );
			//declareParameter( new SqlParameter(Types.DATE) );
			//declareParameter( new SqlParameter(Types.CHAR) );
			//declareParameter( new SqlParameter(Types.DATE) );
			compile();
    	}
    	public Local runQuery(Local local) {
			List result =  execute( new Object[]{
			//For required criteria elements uncomment required values
				//local.getId(),
				//local.getNumeroLocal(),
				//local.getArea(),
				//local.getObservacion(),
				//local.getEstadoFinanciero(),
				//local.getEstado(),
				//local.getUsuarioCrea(),
				//local.getFechaCrea(),
				//local.getUsuarioModifica(),
				//local.getFechaModifica(),
				});
			if ( result.size() > 0 ) {
        		return (Local) result.get(0);
        	} else {
        		return null;
        	}
    	}
    }

    // ------------- FindAllQuery ----------------------------------------    
    class FindAllQuery extends BaseQueryOperation {
		private static final String sql = SELECT
										+ WHERE + " 1=1 ";
    	public FindAllQuery(DataSource ds) {
    		super(ds,sql);
			compile();
    	}
    	public List runQuery() {
			List result =  execute();
			if ( result.size() > 0 ) {
        		return  result;
        	} else {
        		return null;
        	}
    	}
    }

 // ------------- FindAByNumeroLocalQuery ----------------------------------------    
    class FindByNumeroLocalQuery extends BaseQueryOperation {
		private static final String sql = SELECT
										+ WHERE + " NUMERO_LOCAL LIKE ? ";
    	public FindByNumeroLocalQuery(DataSource ds) {
    		super(ds,sql);
    		declareParameter( new SqlParameter(Types.CHAR) );
			compile();
    	}
    	public List runQuery(Local local) {
    		List result =  execute( new Object[]{
    					"%"+local.getNumeroLocal()+"%"
    		});
			if ( result.size() > 0 ) {
        		return  result;
        	} else {
        		return null;
        	}
    	}
    }

    // ------------- FindByActiveStateQuery  -----------------------------
    class FindByActiveStateQuery extends BaseQueryOperation {
		private static final String sql = SELECT
										+ WHERE  + "1=1";
    	public FindByActiveStateQuery(DataSource ds) {
    		super(ds,sql);
			compile();
    	}
    	public Local runQuery(Local local) {
			List result =  execute( new Object[]{
			});
			if ( result.size() > 0 ) {
        		return (Local) result.get(0);
        	} else {
        		return null;
        	}
    	}
    }


    class ListaLocales extends ListaCentroComercialQueryOperation{
		private static final String sql = "SELECT ID,NUMERO_LOCAL as NOMBRE FROM CCO_LOCAL_T";
		public ListaLocales(DataSource ds) {
					super(ds,sql);
					compile();
		}
		public List runQuery() {
				List result =  execute();
				if ( result.size() > 0 ) {
					return result;
				} else {
					return null;
				}
		}
    }   

    class ListaLocalesPorCCO extends ListaCentroComercialQueryOperation{
		private static final String sql = "SELECT LOCAL.ID AS ID,NUMERO_LOCAL as NOMBRE FROM CCO_LOCAL_T LOCAL "										
										+ " WHERE ID_CENTRO_COMERCIAL =? AND LOCAL.ESTADO='DISPONIBLE'";
		public ListaLocalesPorCCO(DataSource ds) {
					super(ds,sql);
					declareParameter( new SqlParameter(Types.INTEGER) );
					compile();
		}
		public List runQuery(Long idcentroComercial) {
			List result =  execute( new Object[]{
					idcentroComercial
			});
				if ( result.size() > 0 ) {
					return result;
				} else {
					return null;
				}
		}
    }   
}
